﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Linq;
using EPiServer.Core;
using EPiServer.Personalization.VisitorGroups;
using EPiServer.PlugIn;
using EPiServer.Web;
using EPiServer.Labs.MobilePack.Core.modules.MobilePack.Core;

namespace EPiServer.Labs.MobilePack.Core
{
    [PagePlugIn]
    public class RedirectionPagePlugin
    {
        public static void Initialize(int bitflags)
        {
            PageBase.PageSetup += PageBase_PageSetup;
        }

        private static PageReference GetPageReference(Guid g)
        {
            var map = PermanentLinkMapStore.Find(g) as PermanentPageLinkMap;
            return (map != null) ? map.PageReference : PageReference.EmptyReference;
        }

        private static void PageBase_PageSetup(PageBase sender, PageSetupEventArgs e)
        {
            if (sender != null)
            {
                if (sender is EditPage)
                {
                    sender.Load += OnLoad;
                }
            }
        }

        private static void OnLoad(object sender, EventArgs e)
        {
            var sender1 = sender as EditPage;
            if (sender1 != null)
            {
                HttpCookie mobileToggleCookie = HttpContext.Current.Request.Cookies["mobileToggle"];

                if (!string.IsNullOrEmpty(sender1.Request["noredirect"]) || (mobileToggleCookie != null && mobileToggleCookie.Value.Equals("normal", StringComparison.InvariantCultureIgnoreCase)))
                {
                    return;
                }

                if (sender1.CurrentPage != null)
                {
                    List<RedirectionRule> redirectionRules = RedirectionRule.Instance.LoadForPage(sender1.CurrentPage);
                    if (redirectionRules != null)
                    {
                        var groupHelper = new VisitorGroupHelper();

                        foreach (RedirectionRule redirectionRule in redirectionRules)
                        {
                            if (groupHelper.IsPrincipalInGroup(Security.PrincipalInfo.CurrentPrincipal, redirectionRule.VisitorGroup) && CheckLanguageCode(redirectionRule, sender1))
                            {
                                sender1.Response.Redirect(DataFactory.Instance.GetPage(GetPageReference(redirectionRule.DestinationPage)).LinkURL, true);
                            }
                        }
                    }

                    var model = ManifestFactory.Instance.LoadModel();
                    if (model != null)
                    {
                        if (DataFactory.Instance.GetDescendents(model.StartPoint).Contains(sender1.CurrentPageLink) || model.StartPoint == sender1.CurrentPageLink)
                        {
                            sender1.Page.ClientScript.RegisterClientScriptBlock(typeof(RedirectionPagePlugin), "offlineupdate", "var webappCache = window.applicationCache;function updateCache() { webappCache.swapCache();console.log('swap cache has been called');}webappCache.addEventListener('updateready', updateCache, false);", true);

                        }

                    }
                }
            }
        }

        private static bool CheckLanguageCode(RedirectionRule redirectionRule, EditPage page)
        {
            if (string.IsNullOrEmpty(redirectionRule.LanguageId))
            {
                return true;
            }

            if (redirectionRule.LanguageId.Equals(page.CurrentPage.LanguageID, StringComparison.InvariantCultureIgnoreCase))
            {
                return true;
            }

            return false;
        }
    }
}
